package leetcode.linkedlist;

import cn.hutool.core.util.StrUtil;

/**
 * 单链表的节点类
 */
public class ListNode {

    /**
     * 节点值
     */
    public int val;

    /**
     * 下一个节点
     */
    public ListNode next;

    /**
     * 构造函数
     */
    public ListNode() {
    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }

    /**
     * 构建链表
     *
     * @param arr 数组
     * @return
     */
    public static ListNode makeLinkedList(Integer[] arr) {
        ListNode head = new ListNode();
        head.val = arr[0];
        ListNode tail = head;
        for (int i = 1; i < arr.length; i++) {

            ListNode node = new ListNode();
            node.val = arr[i];
            tail.next = node;
            tail = tail.next;
        }
        return head;
    }

    /**
     * 遍历链表
     * @return  字符串
     */
    public String list() {
        ListNode head = this;
        StringBuilder str = new StringBuilder(StrUtil.EMPTY);
        while (head != null) {
            str.append(head.val).append("-> ");
            head = head.next;
        }
        return str.toString();
    }
}
